import { message, Popconfirm, Table } from "antd";
import request from "../../axios";
import { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import "./index.css";

const StoreNumber = () => {
  const columns: any[] = [
    {
      title: "商家账号ID",
      dataIndex: "merchantId",
    },
    {
      title: "商家名称",
      dataIndex: "merchantName",
    },
    {
      title: "备注",
      dataIndex: "remarks",
    },
    {
      title: "操作",
      dataIndex: "option",
      valueType: "option",
      width: 120,
      fixed: "right",
      render: (_: any, record: any) => {
        return (
          <Popconfirm
            title="确定要删除商家么"
            onConfirm={async () => {
              try {
                const { code,msg } = await request.delete(
                  `/route/api/chenfeng/${record?.merchantId}`,
                  {
                    accessToken: 1,
                    enterpriseId: counter?.corpId,
                    userId: counter?.staffId
                  }
                );
                await getInitData();
                if(code == 1007) {
                  message.error(msg)
                } else {
                  message.success("删除成功"); 
                }
              } catch (error) {
                console.error("Error getting initial data:", error);
              }
            }}
            okText="确定"
            cancelText="取消"
          >
            <span style={{ color: "rgba(180, 35, 24, 1)" }}>移除</span>
          </Popconfirm>
        );
      },
    },
  ];

  const [allShop, setAllShop] = useState<any>([]);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);

  const counter = useSelector((state: any) => state.counter.data);

  const getInitData = async (
    id = counter?.corpId
  ) => {
    try {
      const { data } = await request.get(
        `/route/api/merchant/getMerchantInCF/${id}`,
        {
          accessToken: 1,
          pageSize: pageSize,
          pageNum: currentPage
        }
      );
      setAllShop(data);
    } catch (error) {
      message.error('请求失败')
      console.error("Error getting initial data:", error);
    }
  };

  const handleTableChange = (current: any, pageSize: any) => {
    setCurrentPage(current);
    setPageSize(pageSize);
  };

  useEffect(() => {
    getInitData();
  }, [currentPage,pageSize]);

  return (
    <div className="container">
      <Table
        columns={columns}
        className="device-log-table"
        dataSource={allShop?.data}
        pagination={{
          showSizeChanger: true,
          pageSizeOptions: ["5", "10", "20"],
          total: allShop?.totalCount || 0,
          current: currentPage,
          pageSize: pageSize,
          onChange: handleTableChange,
        }}
        scroll={{ y: 1000 }}
      />
    </div>
  );
};

export default StoreNumber;
